﻿using JNPF.Logging;
using Microsoft.AspNetCore.Mvc;
using PARK.Accessctl.Entitys.Dto.AccessRecord;
using PARK.Attend.Entitys.Dto.AttendReport;
using PARK.Attend.Entitys.Entity;
using PARK.Attend.Interfaces;
using PARK.ClayObject;
using PARK.Common.Configuration;
using PARK.Common.Core.Manager;
using PARK.Common.Extension;
using PARK.Common.Filter;
using PARK.Common.Helper;
using PARK.Common.Model.NPOI;
using PARK.DataEncryption;
using PARK.Dependency;
using PARK.DynamicApiController;
using PARK.JsonSerialization;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PARK.Attend
{
    /// <summary>
    /// 考勤记录服务
    /// </summary>
    [ApiDescriptionSettings(Tag = "Attend", Name = "Report", Order = 200)]
    [Route("api/attend/[controller]")]
    public class AttendReportService : IAttendReportService, IDynamicApiController, ITransient
    {
        private readonly ISqlSugarRepository<AttendReportEntity> _attendReportRepository;
        private readonly SqlSugarScope _db;
        private readonly IUserManager _userManager;

        /// <summary>
        /// 初始化一个<see cref="AttendReportService"/>类型的新实例
        /// </summary>
        public AttendReportService(
            ISqlSugarRepository<AttendReportEntity> attendReportRepository,
            IUserManager userManager)
        {
            _attendReportRepository = attendReportRepository;
            _db = _attendReportRepository.Context;
            _userManager = userManager;
        }


        #region 获取考勤报表
        /// <summary>
		/// 获取考勤报表
		/// </summary>
		/// <param name="input">请求参数</param>
		/// <returns></returns>
        [HttpGet("")]
        public async Task<dynamic> GetList([FromQuery] AttendRecordListQueryInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                //var sidx = input.sidx == null ? "sortCode" : input.sidx;
                ////打卡日期
                List<string> queryBillDate = input.passtime != null ? input.passtime.Split(',').ToObeject<List<string>>() : null;
                DateTime? startBilldate = queryBillDate != null ? Ext.GetDateTime(queryBillDate.First()) : null;
                DateTime? endBilldate = queryBillDate != null ? Ext.GetDateTime(queryBillDate.Last()) : null;
                var begdate = "";
                var endate = "";
                var departId = "";
                if (startBilldate != null)
                {
                    begdate = Convert.ToDateTime(startBilldate).ToString("yyyy-MM-dd");
                }
                if (endBilldate != null)
                {
                    endate = Convert.ToDateTime(endBilldate).ToString("yyyy-MM-dd");
                }
                if (!string.IsNullOrEmpty(input.departId))
                {
                    departId = input.departId;
                }
                var Pars = new List<SugarParameter>(){
                                        new SugarParameter("@begData",begdate),
                                        new SugarParameter("@endData",endate),
                                        new SugarParameter("@organizeId",departId),
                                        new SugarParameter("@CompanyId",userInfo.companyId)
                                    };
                var data = await _db.Ado.UseStoredProcedure().GetDataTableAsync("P_Rep_Attend", Pars);
                var jsonData = new
                {
                    list = data
                };
                return JsonHelper.ToJson(jsonData);
            }
            else
                return null;
        }
        #endregion

        #region 导出考勤报表Excel
        /// <summary>
        /// 获取考勤报表无分页列表
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        [NonAction]
        public async Task<DataTable> GetNoPagingListReport([FromQuery] AttendRecordListQueryInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                //var sidx = input.sidx == null ? "sortCode" : input.sidx;
                ////打卡日期
                List<string> queryBillDate = input.passtime != null ? input.passtime.Split(',').ToObeject<List<string>>() : null;
                DateTime? startBilldate = queryBillDate != null ? Ext.GetDateTime(queryBillDate.First()) : null;
                DateTime? endBilldate = queryBillDate != null ? Ext.GetDateTime(queryBillDate.Last()) : null;
                var begdate = "";
                var endate = "";
                var departId = "";
                if (startBilldate != null)
                {
                    begdate = Convert.ToDateTime(startBilldate).ToString("yyyy-MM-dd");
                }
                if (endBilldate != null)
                {
                    endate = Convert.ToDateTime(endBilldate).ToString("yyyy-MM-dd");
                }
                if (!string.IsNullOrEmpty(input.departId))
                {
                    departId = input.departId;
                }
                var Pars = new List<SugarParameter>(){
                                        new SugarParameter("@begData",begdate),
                                        new SugarParameter("@endData",endate),
                                        new SugarParameter("@organizeId",departId),
                                        new SugarParameter("@CompanyId",userInfo.companyId)
                                    };
                var data = await _db.Ado.UseStoredProcedure().GetDataTableAsync("P_Rep_Attend", Pars);
                return data;
            }
            else
                return null;

        }

        /// <summary>
        /// 导出考勤报表
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        [HttpGet("Actions/ExportReport")]
        public async Task<dynamic> ExportReport([FromQuery] AttendRecordListQueryInput input)
        {

            var userInfo = await _userManager.GetUserInfo();
            var exportDataNew = new List<AttendReportListOutput>();
            var exportData = await this.GetNoPagingListReport(input);
            exportDataNew = JSON.Serialize(exportData).ToList<AttendReportListOutput>();
            List<ParamsModel> paramList = "[{\"value\":\"工号\",\"field\":\"JobNo\"},{\"value\":\"姓名\",\"field\":\"RealName\"},{\"value\":\"部门\",\"field\":\"DepartName\"},{\"value\":\"应勤天数\",\"field\":\"YdDays\"},{\"value\":\"打卡次数\",\"field\":\"SignTimes\"},{\"value\":\"缺卡次数\",\"field\":\"NoSignTimes\"},{\"value\":\"缺卡日期\",\"field\":\"NoSignDate\"},{\"value\":\"外出次数\",\"field\":\"OutTimes\"},{\"value\":\"事假天数\",\"field\":\"thingDays\"},{\"value\":\"迟到次数\",\"field\":\"LateTimes\"},{\"value\":\"迟到时长\",\"field\":\"Latemins\"},{\"value\":\"迟到日期\",\"field\":\"LateDate\"},{\"value\":\"备注\",\"field\":\"Remark\"}]".ToList<ParamsModel>();
            ExcelConfig excelconfig = new ExcelConfig();
            excelconfig.FileName = userInfo.companyName + "_" + "考勤报表" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
            excelconfig.HeadFont = "微软雅黑";
            excelconfig.HeadPoint = 10;
            excelconfig.IsAllSizeColumn = true;
            excelconfig.ColumnModel = new List<ExcelColumnModel>();
            List<string> selectKeyList = input.selectKey.Split(',').ToList();
            foreach (var item in selectKeyList)
            {
                var isExist = paramList.Find(p => p.field == item);
                if (isExist != null)
                {
                    excelconfig.ColumnModel.Add(new ExcelColumnModel() { Column = isExist.field, ExcelColumn = isExist.value });
                }
            }
            var addPath = FileVariable.TemporaryFilePath + excelconfig.FileName;
            ExcelExportHelper<AttendReportListOutput>.Export(exportDataNew, excelconfig, addPath);
            var fileName = _userManager.UserId + "|" + addPath + "|xls";
            var output = new
            {
                name = excelconfig.FileName,
                //url = "wwwroot/Resources/TemporaryFile/" + excelconfig.FileName
                url = "api/file/Download?encryption=" + DESCEncryption.Encrypt(fileName, "JNPF") //"wwwroot/Template/TemporaryFile/" + excelconfig.FileName //
            };
            return output;
        }
        #endregion
    }
}
